<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /**
           1 4 2
           1 2 4
           1和1连线，4和2连线，其实本题和上一题几乎是完全一模一样的
        */
        /* 
            时间：O(n * m)
            空间：O(n * m)
        */
        var longestCommonSubsequence = function(text1, text2) {
            let len1 = text1.length;
            let len2 = text2.length;
            let dp = new Array(len1 + 1).fill(0).map(() => new Array(len2 + 1).fill(0));
            // dp[i][0]和dp[0][j]都是0，因为text1从0 -> i-1字符串和''空字符串的公共子序列都是0，dp[i][0]的j是0，意味是这个比较的text2的就是空字符串，思考dp数组的定义就能够得出
            // 需要双重for循环
            for (let i = 1; i <= len1; i++) {
                // j需要倒序,倒序的原因是：1. dp[j]需要从上一轮的dp[j - 1]推导出来 2. 正序，可能dp[j - 1]在这一轮又被用了一次
                for (let j = 1; j <= len2; j++) {
                    if (text1[i - 1] === text2[j - 1]) {
                        dp[i][j] = dp[i - 1][j - 1] + 1
                    } else {
                        dp[i][j] = Math.max(dp[i][j - 1], dp[i -1][j])
                    }
                }
            }
            console.log(dp, 'dp');
            return dp[len1][len2]
        };
        // console.log(longestCommonSubsequence('abcde', 'ace'));
        console.log(longestCommonSubsequence('abcde', 'ae'));
        // console.log(findLength([0,0,0,0,0], [0,0,0,0,0]));
    </script>
</body>

</html>